#include "mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>


static MyFile *BuyFile(int fd, int flag)
{
    MyFile *file = (MyFile*)malloc(sizeof(MyFile));  // 申请内存
    if (NULL == file) return NULL;                   // 内存申请失败返回NULL
    
    file->bufferlen = 0;                             // 缓冲区初始长度为0
    file->fileno = fd;                               // 绑定文件描述符
    file->flag = flag;                               // 标记初始化为0
    memset(file->outbuffer, 0, sizeof(file->outbuffer)); // 缓冲区清零
    file->flush_method = LINE_FLUSH;                 // 默认行刷新策略
    
    return file;
}

MyFile *MyFopen(const char *path, const char *mode)
{
    int fd = -1;
    int flag = 0;

    if(strcmp(mode, "w") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "a") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_APPEND;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "r") == 0)
    {
        flag = O_RDWR;
        fd = open(path, flag);
    }
    else 
    {

    }

    if (fd < 0) return NULL;

    return BuyFile(fd, flag);
}

void MyClose(MyFile *file)
{
    if (file->fileno < 0) return;

    MyFFlush(file);
    close (file->fileno);
    free(file);
}

int MyFwrite(MyFile *file, void *str, int len)
{ 
    // 1. 将数据拷贝到输出缓冲区
    memcpy(file->outbuffer + file->bufferlen, str, len);
    file->bufferlen += len;
    
     // 2. 检查是否需要刷新（行刷新逻辑）
    if((file->flush_method & LINE_FLUSH) 
    && file->outbuffer[file->bufferlen - 1] == '\n')    // 缓冲区最后一个字符是换行符
    {
        MyFFlush(file);
    }

    return 0;
}

void MyFFlush(MyFile *file)
{
    if (file->bufferlen <= 0) return;
    
    // 把数据从用户拷贝到内核文件缓冲区中
    int n = write(file->fileno, file->outbuffer, file->bufferlen);
    (void)n;
    fsync(file->fileno);
    file->bufferlen = 0;
}
